// 获取元素 表格
const table = document.querySelector('.list')
const total = document.querySelector('.total')
// 一、渲染函数
const getStudentList = async () => {
  const res = await axios({ url: '/students' })
  const htmlStr = res.data
    .map((item) => {
      return `
    <tr>
                        <td>${item.name}</td>
                        <td>${item.age}</td>
                        <td>${item.gender ? '男' : '女'}</td>
                        <td>第${item.group}组</td>
                        <td>${item.hope_salary}</td>
                        <td>${item.salary}</td>
                        <td>${item.province + item.city + item.area}</td>
                        <td>
                          <a href="javascript:;" class="text-success mr-3"
                            ><i class="bi bi-pen" data-id="${item.id}"></i
                          ></a>
                          <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id="${
                            item.id
                          }"></i></a>
                        </td>
                      </tr>`
    })
    .join('')
  table.innerHTML = htmlStr
  total.innerHTML = res.data.length
}
getStudentList()

// 初始化模态框 & 城市选择
// bootstrap的模态框直接cv即可
const modalBox = document.querySelector('#modal')
const modal = new bootstrap.Modal(modalBox)
const ps = document.querySelector('[name=province]')
const cs = document.querySelector('[name=city]')
const as = document.querySelector('[name=area]')
// 获取form表单
const form = document.querySelector('#form')

// 绑定添加学员，弹出modal层
const openBtn = document.querySelector('#openModal')
openBtn.addEventListener('click', function () {
  form.reset()
  modalBox.dataset.id = 'add'
  modalBox.querySelector('.modal-title').innerHTML = '添加学员'
  modal.show()
})

// 添加学生信息
const submitBtn = document.querySelector('#submit')
submitBtn.addEventListener('click', async function () {
  const data = serialize(form, { hash: true })
  if(!data.name) return alert('名字不能为空')
  if(!data.age) return alert('年龄不能为空')
  if(!data.hope_salary) return alert('期望薪资不能为空')
  if(!data.salary) return alert('薪资不能为空')
  if (!data.group) return alert('组号不能为空')
  if (!data.province) return alert('省份不能为空')
  if (!data.city) return alert('城市不能为空')
  if (!data.area) return alert('地区不能为空')
  if(data.group < 1 || data.group > 8) return alert('组号只能是1-8')
  data.age = +data.age
  data.gender = +data.gender
  data.hope_salary = +data.hope_salary
  data.salary = +data.salary
  data.group = +data.group

  // 修改性别
  modalBox.querySelector('#cb01').checked?  data.gender = 1 : data.gender = 0

  if (modalBox.dataset.id === 'add') {
    const res = await axios({ url: '/students', method: 'post', data })
    modal.hide()
    getStudentList()
    alert(res.message)
  } else {
    const res = await axios({ url: '/students/' + modalBox.dataset.id, method: 'put', data })
    modal.hide()
    getStudentList()
    alert(res.message)
  }
})

// 获取城市信息
// 获取省份
const initCity = async () => {
  const res = await axios({ url: '/api/province' })
  const provinceStr = res.data
    .map((item) => {
      return `<option value="${item}">--${item}--</option>`
    })
    .join('')
  ps.innerHTML = `<option value="">--省份--</option>${provinceStr}`
  ps.addEventListener('change', async function () {
    const res = await axios({ url: '/api/city', params: { pname: ps.value } })
  
    const cityStr = res.data
      .map((item) => {
        return `<option value="${item}">--${item}--</option>`
      })
      .join('')
    cs.innerHTML = `<option value="">--城市--</option>${cityStr}`
    cs.addEventListener('change', async function () {
      const res = await axios({
        url: '/api/area',
        params: { pname: ps.value, cname: cs.value },
      })
     
      const areaStr = res.data
        .map((item) => {
          return `<option value="${item}">--${item}--</option>`
        })
        .join('')
      as.innerHTML = `<option value="">--地区--</option>${areaStr}`
    })
  })
}
initCity()

// 修改学员信息
table.addEventListener('click', async function (e) {
  if (e.target.classList.contains('bi-pen')) {
    // 修改
    const id = e.target.dataset.id
    const { data: res } = await axios({ url: '/students/' + id })
    
    const nodeList = modalBox.querySelectorAll('[name]')
    
    nodeList.forEach((item) => {
    
      if (item.name === 'gender') {
        res[item.name]
          ? (modalBox.querySelector('#cb01').checked = true)
          : (modalBox.querySelector('#cb02').checked = true)
      }
      item.value = res[item.name]
    })
    // 获取城市下拉框
    const { data: cityData } = await axios({
      url: '/api/city',
      params: { pname: res.province },
    })
   
    const cityStr = cityData
      .map((item) => {
        return `<option value="${item}">--${item}--</option>`
      })
      .join('')
    cs.innerHTML = `<option value="">--城市--</option>${cityStr}`
    cs.value = res.city

    // 获取地区下拉框
    const { data: areaData } = await axios({
      url: '/api/area',
      params: { pname: res.province, cname: res.city },
    })
  
    const areaStr = areaData
      .map((item) => {
        return `<option value="${item}">--${item}--</option>`
      })
      .join('')
    as.innerHTML = `<option value="">--城市--</option>${areaStr}`
    as.value = res.area
    modalBox.dataset.id = id
    modalBox.querySelector('.modal-title').innerHTML = '修改学员信息'
    modal.show()
  }
  if (e.target.classList.contains('bi-trash')) {
    // todo
    // 删除
    const id = e.target.dataset.id
    const res = await axios({ url: '/students/' + id, method: 'DELETE' })
    getStudentList()
    alert('删除成功')
  }
})
